#include "QMsgTextEdit.h"

#include <QMovie>

QMsgTextEdit::QMsgTextEdit(QWidget* parent)
    : QTextEdit(parent) {
}

QMsgTextEdit::~QMsgTextEdit() {
    deleteAllEmotionImage();
}

void QMsgTextEdit::onEmotionFrameChange(int frame) {
    QMovie* movie = qobject_cast<QMovie*>(sender());
    document()->addResource(QTextDocument::ImageResource, QUrl(emotionMap.value(movie)), movie->currentPixmap());
}

void QMsgTextEdit::addEmotionUrl(int emotionNum) {
    const QString& imageName = QString("qrc:/resource/img/emojiqq/%1.gif").arg(emotionNum);
    const QString& flageName = QString("%1").arg(imageName);
    // width:25px;height:25px;vertical-align:middle;
    insertHtml(QString("<img src='%1'width=\"%2\" height=\"%3\" class=\"emoj\"/>").arg(imageName).arg(25).arg(25));
    // insertHtml(QString("<img src='%1' width: \"12px\" height:\"12px\" />").arg(imageName));
    if (listEmotionUrl.contains(imageName)) {
        return;
    }
    else {
        listEmotionUrl.append(imageName);
    }

    QMovie* apngMovie = new QMovie(imageName, "apng", this);
    emotionMap.insert(apngMovie, flageName);

    // 数据帧改变时发送的信号
    // connect(apngMovie, SIGNAL(frameChange(int)), this, SLOT(onEmotionFrameChange(int)));
    apngMovie->start();
    updateGeometry();
}

void QMsgTextEdit::deleteAllEmotionImage() {
    for (auto itor = emotionMap.constBegin(); itor != emotionMap.constEnd(); itor++) {
        delete itor.key();
    }

    emotionMap.clear();
}

void QMsgTextEdit::addFileUrl(QString fileUrl) {
    insertHtml(QString("<file src='%1' class=\"file\" />").arg(fileUrl));
}

void QMsgTextEdit::addImageUrl(QString fileUrl) {
    insertHtml(QString("<img src='%1' class=\"img\" />").arg(fileUrl));
}
